var util = require('../../utils/util.js');
import {
  SoundPlayer
} from "../../utils/soundPlayer.js";
var date_util = require('../../utils/date_util.js');
var api = require('../../config/api.js');
var version = require('../../config/version.js');
var user = require('../../services/user.js');
const QR = require('../../utils/wxqrcode.js');
var event = require('../../utils/event.js');
var player = new SoundPlayer();
var app = getApp();
var qrcode;
const navigationBarHeight = (getApp().statusBarHeight + 44) + 'px'
Page({
  data: {
    navigationBarTitle: '我的',
    navigationBarHeight,
    tabbar: {},
    isIphoneX: app.globalData.isIphoneX ? true : false,
    winHeight: 0,
    winWidth: 0,
    // 用户授权
    userInfo: app.globalData.userInfo,
    systemInfo: {},
    hasUserInfo: app.globalData.hasUserInfo,
    auth: app.globalData.auth,
    hasPhone: app.globalData.hasPhone,
    getUserInfoFail: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    buyList: [],
    memoryList: [],
    selectedFlag: [],
    hiddenShare: true,

    qrcode: '',

    //轮播相关
    preIndex: 0,
    displayCommId: 0,
    faAutoplay: false,
    faIndicatorDots: false,
    //音频、视频播放相关
    isPlay: false,
    //自定义轮播
    curIndex: 0, //当前显示的view下标
    swiperList: [1, 2, 3, 4, 5, 6, 7, 8, 9], //轮播数据列表
    itemWidth: 0, //单个轮播图swiper-item的宽度；
    itemHeight: 0, //单个轮播图swiper-item的高度；
    allWidth: 0, //轮播展示 swiper的总宽度；
    scale: 0.9, //  缩放大小倍数；
    startClinetX: '', //触摸开始位置；
    startTimestamp: '', //触摸开始时间；
    translateDistance: 0, //动画移动的 距离；
    animationToLarge: {}, //从小变大的动画；
    animationToSmall: {},

    flag: 0,
    iidex: 0,

    userStatis: null,
    showErrorBtn: false,
  },

  onSlideChangeEnd: function(e) {
    var that = this;
    var current = e.detail.current
    if (e.detail.source == "touch") {
      if (current == 0 && this.data.preIndex > 1) {
        this.setData({
          displayCommId: this.data.preIndex
        });
      } else {
        this.setData({
          preIndex: current
        });
        let qrcodeSize = this.getQRCodeSize()
        this.createQRCode(this.data.buyList[this.data.preIndex].secret, qrcodeSize)
      }
    }
  },
  //
  //适配不同屏幕大小的canvas
  getQRCodeSize: function() {
    var size = 0;
    try {
      var res = wx.getSystemInfoSync();
      var scale = res.windowWidth / 750; //不同屏幕下QRcode的适配比例；设计稿是750宽
      var width = 300 * scale;
      size = width;
    } catch (e) {
      size = 150;
    }
    return size;
  },
  createQRCode: function(text, size) {
    //调用插件中的draw方法，绘制二维码图片
    let that = this
    try {
      let _img = QR.createQrCodeImg(text, {
        size: parseInt(size)
      })
      that.setData({
        'qrcode': _img
      })
    } catch (e) {}
  },
  //
  onLoad: function(options) {
    wx.hideTabBar();
    app.editTabbar();
    var that = this;

    wx.showShareMenu({ // 要求小程序返回分享目标信息      
      withShareTicket: true
    });

    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          systemInfo: res,
          winWidth: res.windowWidth,
          winHeight: res.windowHeight,
          itemWidth: res.windowWidth * 0.4,
        });
      }
    });
    wx.hideShareMenu();
    //动画
    this.animation = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 500,
      timingFunction: "ease-out",
      delay: 0
    })
  },
  onMyevent: function(e) {
    var that = this
    that.setData({
      userInfo: e.detail.paramBtoA.userInfo,
      hasUserInfo: e.detail.paramBtoA.hasUserInfo,
      auth: e.detail.paramBtoA.auth,
      hasPhone: e.detail.paramBtoA.hasPhone,
    })
    if (that.data.auth && that.data.hasPhone) {
      that.GetStatis();
      that.GetMemory();
      event.emit('AuthChanged');
    }
  },

  onReady: function() {},
  onShow: function() {
    var that = this
    that.setData({
      userInfo: app.globalData.userInfo,
      hasUserInfo: app.globalData.hasUserInfo,
      auth: app.globalData.auth,
      hasPhone: app.globalData.hasPhone,
    })
    console.log(that.data.hasPhone)
    if (that.data.auth && that.data.hasPhone) {
      that.GetMemory();
      that.GetStatis();
    } else {
      that.auth = that.selectComponent("#auth");
      util.getScope('scope.userInfo').then(function(resss) {
        if (resss) {
          that.auth.hideAuth();
          ///防止緩存失效带来的问题
          let code = null;
          return that.login().then((res) => { //userInfo
            code = res.code;
            wx.getUserInfo({
              withCredentials: true,
              success: function(res_user) {
                //先去登陆        
                wx.request({
                  url: api.userAuth,
                  data: {
                    platform: 'wx',
                    authorizationCode: code,
                    userEncryptrfData: res_user.encryptedData,
                    iv: res_user.iv
                  },
                  method: 'POST',
                  header: {
                    'Content-Type': 'application/json',
                    'accessToken': wx.getStorageSync('token'),
                    'appVersion': version.appVersion,
                    'deviceModel': getApp().globalData.systemInfo.model,
                    'platform': 'wx',
                    'build': version.build,
                    'deviceMachineCode': '',
                    'deviceOS': getApp().globalData.systemInfo.system.split(" ")[0],
                    'deviceOSVersion': getApp().globalData.systemInfo.system
                  },
                  success: function(res) {
                    if (res && res.statusCode == 200 && res.data.code == 200) {
                      wx.setStorageSync('token', res.data.data.token);
                      app.globalData.token = res.data.data.token;
                      var userInfo = res.data.data.user
                      if (userInfo && !userInfo.avatarUrl) {
                        userInfo.avatarUrl = version.defaultAvataUrl
                      }
                      var uuid = userInfo.id;
                      wx.setStorageSync('userInfo', userInfo);
                      app.globalData.userInfo = userInfo
                      app.globalData.hasUserInfo = true
                      app.globalData.auth = true
                      wx.setStorageSync('auth', true);
                      app.globalData.hasPhone = true
                      wx.setStorageSync('hasPhone', true);
                      that.setData({
                        auth: true,
                        userInfo: app.globalData.userInfo,
                        hasUserInfo: app.globalData.hasUserInfo,
                        hasPhone: app.globalData.hasPhone,
                      });
                      that.GetMemory();
                      that.GetStatis();                     
                    }
                    if (res && res.data.code == 301) {
                      wx.setStorageSync('token', res.data.data.token);
                      app.globalData.token = res.data.data.token;
                      app.globalData.hasPhone = false
                      wx.setStorageSync('hasPhone', false);
                      that.setData({
                        hasPhone: false,
                      });
                      that.auth.showAuth();
                    }
                  }
                })
              }
            })
          })
          //防止緩存失效带来的问题
        } else {
          that.auth.showAuth();
        }
      })
      //else
    }

  },
  onHide: function() {},
  onUnload: function() {},
  login: function() {
    return new Promise(function(resolve, reject) {
      wx.login({
        success: function(res) {
          if (res.code) {
            //登录远程服务器
            resolve(res);
          } else {
            reject(res);
          }
        },
        fail: function(err) {
          reject(err);
        }
      });
    });
  },
  GetStatis: function() {
    util.pututrequest(api.userStatis + '?userId=' + this.data.userInfo.id, "GET").then(res => {
      if (res && res.code == 200) {
        this.setData({
          userStatis: res.data
        })
      }
    })
  },
  //已购
  GetMyBuy: function() {
    util.pututrequest(api.ticketList + '?uid=' + this.data.userInfo.uuid, "GET").then(res => {
      if (res.success) {
        var k = 0;
        var ticket = []
        var tickets = res.data
        if (tickets && tickets.length > 0) {
          for (var item in tickets) {
            var ticketJson = tickets[item]['activity']
            var act = ticketJson
            var begin = date_util.convertTime(act.begin_time);
            var end = date_util.convertTime(act.end_time);
            var title_str = act.title.length > 19 ? act.title.substr(0, 16) + '...' : act.title;
            act.begin = begin
            act.end = end
            act.title_str = title_str
            act.id = k
            k = k + 1

            var tickInfo = tickets[item]['ticket']
            var secret = tickInfo.secret
            act.secret = secret
            ticket.push(act)
            // 生成二维码
            let qrcodeSize = this.getQRCodeSize()
            this.createQRCode(secret, qrcodeSize)
            // 生成二维码 
          }
        }
        this.setData({
          buyList: ticket
        })
      }
    })
  },
  //回忆
  GetMemory: function() {
    var that = this
      util.pututrequest(api.memoryList + '?userId=' + this.data.userInfo.id + "&sjs=" + (new Date()).getTime(), "GET").then(res => {
        if (res && res.code == 200) {
          var k = 0;
          var acts = []
          var res_acts = res.data
          if (res_acts) {
            var tickets = res_acts.memoryGroups
            for (var item in tickets) {
              var one_act = {}
              one_act.key = tickets[item]['monthYear']
              one_act.value = tickets[item]['memories']
              acts.push(one_act)
            }
          }
          this.setData({
            memoryList: acts,
            showErrorBtn: true
          })
        }
      })
  },

  // 展开折叠选择  
  changeToggle: function(e) {
    var index = e.currentTarget.dataset.index;
    if (this.data.selectedFlag[index]) {
      this.data.selectedFlag[index] = false;
    } else {
      this.data.selectedFlag[index] = true;
    }

    this.setData({
      selectedFlag: this.data.selectedFlag
    })
  },

  sharePic: function(e) {
    let index = e.currentTarget.dataset.index
    var act = this.data.buyList[index]
    util.pututrequest(api.shareActivity + '?uuid=' + act.uuid + '&type=ACTIVITY', 'GET').then(res => {
      if (res.success) {
        this.setData({
          hiddenShare: false,
          shareindex: index,
          sharepicurl: res.data.path
        })
      }
    })
  },
  close_share: function(e) {
    this.setData({
      hiddenShare: true
    })
  },
  saveNetPicToLocal: function() {
    var imgPath = this.data.sharepicurl
    wx.downloadFile({
      url: imgPath,
      success: function(res) {
        //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(data) {
            wx.showModal({
              title: '保存成功',
              content: '活动海报保存到相册成功',
              confirmText: "我知道了",
              showCancel: false,
            })
          },
          fail: function(err) {
            if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              // console.log("当初用户拒绝，再次发起授权")
              wx.openSetting({
                success(settingdata) {
                  // console.log(settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    // console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                    wx.showToast({
                      title: '授权成功，继续保存',
                      icon: 'success',
                      duration: 2000
                    })
                  } else {
                    // console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                    wx.showToast({
                      title: '未授权，无法保存',
                      icon: 'success',
                      duration: 2000
                    })
                  }
                }
              })
            }
          },
          complete(res) {

          }
        })
      }
    })
  },
  onShareAppMessage: function(res) {
    var act = this.data.buyList[this.data.shareindex]
    if (res.from === 'button') { //页面内转发   menu 菜单转发

    }
    return {
      title: 'Metoo现场',
      desc: act.title,
      path: '/pages/detail/detail?uuid=' + act.uuid + '&source=app&commId=0&type=0',
      imageUrl: this.data.sharepicurl,
      success: function(res) { // 转发成功       
        var shareTickets = res.shareTickets;
        if (shareTickets.length == 0) {
          return false;
        }
        //可以获取群组信息
        if (this.data.systemInfo.platform == 'android' && (shareTickets.length > 0)) {
          wx.getShareInfo({
            shareTicket: shareTickets[0],
            success: function(res) {
              wx.showToast({
                title: "分享成功",
                duration: 2000
              });
            },
            fail: function() {
              wx.showToast({
                title: "分享失败",
                duration: 2000
              });
            }
          })
        }
        if (this.data.systemInfo.platform == 'ios' && (shareTickets.length > 0)) {
          wx.showToast({
            title: "分享成功",
            duration: 2000
          });
        }
      },
      fail: function(res) { // 转发失败        
        wx.showToast({
          title: "分享失败，请重新分享",
          duration: 2000
        });
      }
    }
  },

  shareActivity: function() { //1.2.0 处理转发 兼容性
    if (wx.canIUse) {
      if (wx.canIUse('button.open-type.share')) {
        return;
      }
    }
    wx.showModal({
      title: '提示',
      content: '当前微信版本过低，无法使用该功能，请点击右上角<转发>菜单进行分享。'
    });
  },
  //// 播放音频
  audioPlay: function(e) {
    var that = this,
      id = e.currentTarget.dataset.id,
      path = e.currentTarget.dataset.path,
      key = e.currentTarget.dataset.key,
      memoryList = that.data.memoryList;
    path = 'https://blcclb.com/' + path;

    for (var i = 0; i < memoryList.length; i++) {
      var one_act = memoryList[i]
      // 处理视频 音频 播放标记
      if (one_act.value && one_act.value.length > 0) {
        for (var iitem in one_act.value) {
          var oneact = one_act.value[iitem]
          if (oneact.comments && oneact.comments.length > 0) {
            var oneactcomments = oneact.comments;
            for (var iiitem in oneactcomments) {
              if (oneactcomments[iiitem].id == id) {
                oneactcomments[iiitem].isPlay = true;
                break;
              }

            }
          }
        }
      }
    }

    that.setData({
      memoryList: memoryList
    })
    player.play(path, () => {

    });
  },
  // 停止音频
  audioStop: function(e) {
    var that = this,
      id = e.currentTarget.dataset.id,
      key = e.currentTarget.dataset.key,
      path = e.currentTarget.dataset.path,
      memoryList = that.data.memoryList;
    path = 'https://blcclb.com/' + path;
    //切换显示状态
    for (var i = 0; i < memoryList.length; i++) {
      var one_act = memoryList[i]
      // 处理视频 音频 播放标记
      if (one_act.value && one_act.value.length > 0) {
        for (var iitem in one_act.value) {
          var oneact = one_act.value[iitem]
          if (oneact.comments && oneact.comments.length > 0) {
            var oneactcomments = oneact.comments;
            for (var iiitem in oneactcomments) {
              if (oneactcomments[iiitem].id == id) {
                oneactcomments[iiitem].isPlay = false;
                break;
              }

            }
          }
        }
      }
    }

    that.setData({
      memoryList: memoryList
    })
    player.stop()
  },

  //轮播效果
  //轮播效果
  //触摸开始的事件
  swiperTouchstart: function(e) {
    var a = e.currentTarget.dataset.index
    var b = e.currentTarget.dataset.iindex
    if (b != this.data.iindex) {
      this.setData({
        flag: 0,
        translateDistance: 0
      })
    }
    if (a != this.data.flag && b == this.data.iindex) {
      this.setData({
        flag: 0,
        translateDistance: 0
      })
    }
    let startClinetX = e.changedTouches[0].clientX;
    this.setData({
      flag: a,
      iindex: b,
      startClinetX: startClinetX, //触摸开始位置；
      startTimestamp: e.timeStamp, //触摸开始时间；
    })
  },

  //触摸移动中的事件
  swiperTouchmove: function(e) {},

  //触摸结束事件
  swiperTouchend: function(e) {
    let times = e.timeStamp - this.data.startTimestamp, //时间间隔；
      distance = e.changedTouches[0].clientX - this.data.startClinetX; //距离间隔；
    //判断
    if (times < 500 && Math.abs(distance) > 10) {
      let curIndex = this.data.curIndex;

      let x0 = this.data.itemWidth,
        x1 = this.data.translateDistance,
        x = 0;
      if (distance > 0) { //手右滑  卡片往左走

        curIndex = curIndex - 1
        if (curIndex < 0) {
          curIndex = 0;
          x0 = 0;
        }
        x = x1 + x0;
      } else { //手左滑  卡片往右走
        curIndex = curIndex + 1
        if (curIndex >= this.data.memoryList[this.data.iidex].value[this.data.flag].comments.length) {
          curIndex = this.data.memoryList[this.data.iidex].value[this.data.flag].comments.length - 1;
          x0 = 0;
        }
        x = x1 - x0;
      }
      this.animationToLarge(curIndex, x);
      this.animationToSmall(curIndex, x);
      this.setData({
        curIndex: curIndex,
        translateDistance: x
      })

    } else {

    }
  },
  animationToLarge: function(curIndex, x) {
    this.animation.translateX(x).scale(1).step()
    this.setData({
      animationToLarge: this.animation.export()
    })
  },
  animationToSmall: function(curIndex, x) {
    this.animation.translateX(x).scale(0.9).step()
    this.setData({
      animationToSmall: this.animation.export()
    })
  },
  animationToCenter: function(curIndex, x) {
    this.animation.translateX(x).scale(1.5, 0.9).step()
    this.setData({
      animationToSmall: this.animation.export()
    })
  },


  goUpload: function(e) {
    var that = this;
    if (!that.data.isShowDate) {
      wx.navigateTo({
        url: '/pages/search/search',
        success: function() {},
        fail: function() {},
        complete: function() {}
      })
    }
  },

  gotoStrength: function(e) {
    wx.navigateTo({
      url: '/pages/strength/strength',
      success: function() {},
      fail: function() {},
      complete: function() {}
    })
  },
  onPullDownRefresh() {
    var that = this
    that.GetStatis();
    that.GetMemory();
    wx.stopPullDownRefresh();
  },

})